package cn.spring.rabbitmq.demo.rabbitmq.sender;

import cn.spring.rabbitmq.demo.rabbitmq.message.DemoMessage;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 * @Author tanyong
 * @Version MessageSender v1.0.0 2025/9/15 17:43 $$
 */
@Component
public class MessageSender {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${rabbitmq.fanout.exchange:fanout-exchange}")
    private String fanoutExchange;

    @Value("${rabbitmq.topic.exchange:topic-exchange}")
    private String topicExchange;

    @Value("${rabbitmq.delay.exchange:delay.exchange}")
    private String delayExchange;


    /**
     * 发送消息到队列demo.queue
     *
     * @param message
     */
    public void basicSend(DemoMessage message) {
        rabbitTemplate.convertAndSend("demo.queue", message);
    }


    /**
     * 发送消息到广播exchange
     *
     * @param message
     */
    public void fanoutSend(DemoMessage message) {
        rabbitTemplate.convertAndSend(fanoutExchange, "", message);
    }

    /**
     * 发送消息到topic exchange
     *
     * @param message    消息内容
     * @param routingKey 路由键
     */
    public void topicSend(DemoMessage message, String routingKey) {
        rabbitTemplate.convertAndSend(topicExchange, routingKey, message);
    }

    /**
     * 发送延迟消息
     *
     * @param message 消息内容
     * @param delay   延迟时间（毫秒）
     */
    public void delaySend(DemoMessage message, long delay) {
        rabbitTemplate.convertAndSend(delayExchange, "delay", message, msg -> {
            if (delay > 0) {
                msg.getMessageProperties().setExpiration(String.valueOf(delay));
            }
            return msg;
        });
    }

    /**
     * 批量发送消息
     *
     * @param messages 消息列表
     */
    public void batchSend(List<DemoMessage> messages) {
        messages.forEach(message -> {
            rabbitTemplate.convertAndSend("batch.exchange", "batch", message, msg -> {
                // 自定义消息属性
                return msg;
            });

        });
    }
}
